<template>
  <div class="cart-outer">
    <div class="cart">
      <div class="cart-container">
        <!-- 空购物车 -->
        <div
          class="empty-cart-top"
          v-if="!cartStore.cartArr">
          <h2 class="login-tip">您的购物车还是空的！</h2>
          <p
            class="login-desc"
            v-if="!userStore.userInfo">
            登录后将显示您之前加入的商品
          </p>
          <router-link
            v-if="!userStore.userInfo"
            to="/login"
            class="btn btn-login">
            立即登录
          </router-link>
          <router-link
            :to="{
              path: '/search',
              query: {
                keyword: '全部商品'
              }
            }"
            class="btn btn-shopping">
            马上去购物
          </router-link>
        </div>
        <!-- 有商品的购物车 -->
        <div
          class="cart-warp"
          v-if="cartStore.cartArr">
          <div
            class="addonitems-tips"
            v-if="69 - total > 0">
            <div>还需 {{ 69 - total }} 元可免运费</div>
          </div>
          <div class="cart-goods-list">
            <div class="cart-head clearfix">
              <div class="col col-check">
                <Checkbox
                  @click.native="changeAllGoodsChecked"
                  ref="allCheck"></Checkbox>
                全选
              </div>
              <div class="col col-img">&nbsp;</div>
              <div class="col col-name">商品名称</div>
              <div class="col col-price">单价</div>
              <div class="col col-num">数量</div>
              <div class="col col-total">小计</div>
              <div class="col col-action">操作</div>
            </div>
            <div class="cart-body">
              <div class="list-item">
                <div class="item-box">
                  <div class="item-table">
                    <div
                      class="item-row clearfix"
                      v-for="goods in goodsInfos"
                      :key="goods.goodsInfo_id">
                      <div class="col col-check">
                        <Checkbox
                          @click.native="changeGoodsChecked(goods)"
                          ref="checkbox"
                          :checked="goods.goods_checked"></Checkbox>
                      </div>
                      <div class="col col-img">
                        <RouterLink
                          target="_blank"
                          class="thumb"
                          :to="{
                            path: '/detail',
                            query: { goods_id: goods.goods_id }
                          }">
                          <img
                            v-lazyload="goods.goods_image"
                            alt=""
                            style="width: 80px; height: 80px" />
                        </RouterLink>
                      </div>
                      <div class="col col-name">
                        <h3 class="name">
                          <RouterLink
                            target="_blank"
                            :to="{
                              path: '/detail',
                              query: { goods_id: goods.goods_id }
                            }">
                            {{
                              `${goods.goods_name} ${goods.goods_version} ${goods.goods_color}`
                            }}
                          </RouterLink>
                        </h3>
                      </div>
                      <div class="col col-price">{{ goods.goods_price }}元</div>
                      <div class="col col-num">
                        <div class="change-goods-num clearfix">
                          <a
                            href="javascript:;"
                            @click="subGoodsCount(goods)">
                            <i>-</i>
                          </a>
                          <input
                            @input="modGoodsCount(goods)"
                            v-model.number="goods.goods_count"
                            type="text"
                            min="1"
                            autocomplete="off"
                            class="goods-num" />
                          <a
                            href="javascript:;"
                            @click="addGoodsCount(goods)">
                            <i>+</i>
                          </a>
                        </div>
                      </div>
                      <div class="col col-total">
                        <span>{{ goods.goods_total }}元</span>
                      </div>
                      <div class="col col-action">
                        <i @click="delGoods(goods)">×</i>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="placeholder-div"></div>
          <div class="cart-bar clearfix">
            <div class="section-left">
              <router-link
                :to="{
                  path: '/search',
                  query: {
                    keyword: '全部商品'
                  }
                }"
                class="btn btn-shopping">
                继续购物
              </router-link>
              <span class="cart-total">
                已选择
                <i>{{ totalNum }}</i>
                件
              </span>
            </div>
            <div class="total-price">
              合计:
              <em>{{ total }}</em>
              元
              <a
                href="javascript:;"
                @click="goOrder">
                去结算
              </a>
            </div>
          </div>
        </div>
        <div class="cart-bottom">
          <Recommend></Recommend>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watchEffect, watch } from 'vue'
import { useRouter } from 'vue-router'
import useGoodsInfos from '@/hooks/useGoodsinfos'
import useDebounce from '@/hooks/useDebounce'
import useMessage from '@/hooks/useMessage'
import useStore from '@/store'
import Recommend from '@/components/recommend/index.vue'
import Checkbox from '@/components/checkbox/index.vue'

const router = useRouter()
const { cartStore, userStore } = useStore()
cartStore.saveCartInLocalStorage()
cartStore.getCartByLocalStorage()
const subGoodsCount = (goods: any) => {
  const result = cartStore.cartArr?.filter(
    item => item.goodsInfo_id == goods.goodsInfo_id
  )
  result && result![0].goods_count > 1 && result![0].goods_count--
  cartStore.saveCartInLocalStorage()
}
const addGoodsCount = (goods: any) => {
  const result = cartStore.cartArr?.filter(
    item => item.goodsInfo_id == goods.goodsInfo_id
  )
  result && result![0].goods_count++
  cartStore.saveCartInLocalStorage()
}
const modGoodsCount = (goods: any) => {
  useDebounce(() => {
    const result = cartStore.cartArr?.filter(
      item => item.goodsInfo_id == goods.goodsInfo_id
    )
    result && (result![0].goods_count = goods.goods_count)
    cartStore.saveCartInLocalStorage()
    console.log(1)
  }, 1000)
}
const changeAllGoodsChecked = () => {
  if (allCheck.value) {
    cartStore.cartArr?.forEach((item, index) => {
      item.goods_checked = allCheck.value!.checked
      checkbox.value![index].checked = allCheck.value!.checked
    })
  }
  cartStore.saveCartInLocalStorage()
}
const changeGoodsChecked = (goods: any) => {
  const result = cartStore.cartArr?.filter(
    item => item.goodsInfo_id == goods.goodsInfo_id
  )
  if (result) result![0].goods_checked = !result![0].goods_checked
  cartStore.saveCartInLocalStorage()
}

const delGoods = (goods: any) => {
  changeShowDialog()
  useMessage({ title: '提示', text: '确认删除所选商品吗？' }).then(
    () => {
      const index = cartStore.cartArr!.findIndex(
        item => goods.goodsInfo_id === item.goodsInfo_id
      )
      cartStore.cartArr!.splice(index!, 1)
      cartStore.saveCartInLocalStorage()
      userStore.userInfo &&
        cartStore.delCart(goods.goodsInfo_id, userStore.userInfo.user_id)
    },
    () => {}
  )
}

const showDialog = ref<boolean>(false)
const changeShowDialog = () => {
  showDialog.value = !showDialog.value
}

let goodsInfos = ref()
watch(
  () => cartStore.cartArr,
  async (newValue, oldValue) => {
    if (newValue && newValue!.length > 0) {
      goodsInfos.value = (await useGoodsInfos()).value
    }
  },
  { immediate: true, deep: true }
)

const total = computed(() => {
  let total = 0
  goodsInfos.value &&
    goodsInfos.value.forEach((e: any) => {
      if (e.goods_checked) total += e.goods_total
    })
  return total
})
const totalNum = ref<number>(0)
const allCheck = ref<InstanceType<typeof Checkbox>>()
const checkbox = ref<InstanceType<typeof Checkbox>[]>()
watchEffect(() => {
  if (checkbox.value && checkbox.value.length > 0) {
    const r = checkbox.value.filter(item => item.checked)
    totalNum.value = r.length
    r.length === checkbox.value.length
      ? (allCheck.value!.checked = true)
      : (allCheck.value!.checked = false)
  }
})
const goOrder = () => {
  userStore.userInfo ? router.push('/order') : router.push('/login')
}
</script>

<style lang="less" scoped>
.cart-outer {
  padding: 38px 0;
  background: #f5f5f5;
  .cart {
    width: 1226px;
    margin: 0 auto;
    .cart-container {
      .empty-cart-top {
        height: 273px;
        padding-left: 558px;
        margin: 65px 0 130px;
        background: url(https://cdn.cnbj1.fds.api.mi-img.com/staticsfile/cart/cart-empty.png)
          no-repeat 124px 0;
        color: #b0b0b0;
        overflow: hidden;
        .login-tip {
          margin: 70px 0 0 0;
          font-size: 36px;
          color: #b0b0b0;
          font-weight: bold;
        }
        .login-desc {
          margin: 0;
          font-size: 20px;
          color: #b0b0b0;
        }
        .btn {
          width: 170px;
          height: 48px;
          line-height: 48px;
          margin-top: 20px;
          background: #ff6700;
          border-color: #ff6700;
          color: #fff;
          display: inline-block;
          text-align: center;
          border: 1px solid #ff6700;
        }
        .btn-login {
          margin-right: 10px;
        }
        .btn-shopping {
          background-color: #f5f5f5;
          color: #ff6700;
        }
      }
      .cart-warp {
        .addonitems-tips {
          text-align: right;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.54);
          line-height: 20px;
          margin-bottom: 13px;
        }
        .cart-goods-list {
          background-color: #fff;
          .cart-head {
            height: 70px;
            line-height: 70px;
            padding-right: 26px;
            color: #424242;
          }
          .cart-body {
            .list-item {
              .item-box {
                padding: 15px 26px 15px 0;
                border-top: 1px solid #e0e0e0;
                .item-table {
                  display: table;
                  border-collapse: collapse;
                  border-spacing: 0;
                  .item-row {
                    display: table-row;
                  }
                }
              }
            }
          }
          .col {
            display: table-cell;
            vertical-align: middle;
          }
          .col-check {
            width: 110px;
            .checkbox {
              margin-left: 24px;
              margin-right: 15px;
            }
          }
          .col-img {
            width: 120px;
          }
          .col-name {
            width: 380px;
            .name {
              line-height: 1;
              margin-top: 8px;
              margin-bottom: 8px;
              font-size: 18px;
              font-weight: 400;
              text-overflow: ellipsis;
              white-space: nowrap;
              overflow: hidden;
            }
          }
          .col-price {
            width: 140px;
            padding-right: 18px;
            text-align: center;
            color: #424242;
          }
          .col-num {
            width: 150px;
            text-align: center;
            color: #424242;
            .change-goods-num {
              width: 148px;
              height: 38px;
              border: 1px solid #e0e0e0;
              text-align: center;
              background-color: #fff;
              position: relative;
              zoom: 1;
              a {
                float: left;
                width: 38px;
                height: 38px;
                line-height: 38px;
                color: #757575;
                transition: all 0.3s;
                font-size: 20px;
              }
              .goods-num {
                float: left;
                width: 72px;
                height: 38px;
                line-height: 38px;
                padding: 0;
                border-width: 0;
                color: #424242;
                font-size: 16px;
                outline: 0;
                text-align: center;
              }
            }
          }
          .col-total {
            width: 120px;
            padding-right: 81px;
            text-align: right;
            span {
              font-size: 16px;
              color: #ff6700;
            }
          }
          .col-action {
            width: 80px;
            text-align: center;
            i {
              display: inline-block;
              font-size: 20px;
              width: 20px;
              height: 20px;
              line-height: 20px;
              border-radius: 50%;
              transition: 0.5s;
              cursor: pointer;
              &:hover {
                color: #fff;
                background-color: rgb(229, 57, 53);
              }
            }
          }
        }
        .placeholder-div {
          margin: 20px 0;
        }
        .cart-bar {
          // position: fixed;
          // width: 1226px;
          // left: 50%;
          // margin-left: -613px;
          // bottom: 0;
          // z-index: 20;
          // background-color: #fafafa;
          // box-shadow: 0 -3px 6px rgb(0 0 0 / 10%);
          height: 50px;
          text-align: right;
          background-color: #fff;
          transition: background 0.3s ease, top 0.3s ease;
          position: relative;
          .section-left {
            float: left;
            a {
              line-height: 50px;
              margin-left: 32px;
              color: #757575;
              text-decoration: none;
              transition: 0.5s;
              &:hover {
                color: #ff6700;
              }
            }
            .cart-total {
              margin-left: 16px;
              padding-left: 16px;
              border-left: 1px solid #eee;
              color: #757575;
              i {
                color: #ff6700;
              }
            }
          }
          .total-price {
            padding-left: 13px;
            text-align: right;
            color: #ff6700;
            em {
              font-style: normal;
              font-size: 30px;
              padding-left: 13px;
              color: #ff6700;
              height: 50px;
              text-align: right;
            }
            a {
              width: 200px;
              height: 48px;
              line-height: 48px;
              font-size: 18px;
              margin-left: 50px;
              vertical-align: top;
              background: #ff6700;
              border-color: #ff6700;
              color: #fff;
              display: inline-block;
              border: 1px solid #ff6700;
              text-align: center;
              cursor: pointer;
              transition: all 0.4s;
              &:hover {
                background: #f25807;
                border-color: #f25807;
              }
            }
          }
        }
      }
    }
  }
}
</style>
